import useAddr from './useAddr.js'

import {
	showToast
} from 'vant';
import router from '@/router';
import {
	addCart as addCartApi
} from '@/api/goods'

import checkLogin from '@/utils/checkLogin'

import {ref} from 'vue'
export default function(activeSku, popupState) {
	const {
		defaultAddr
	} = useAddr()
	const buy_num = ref(1)

	function addCart() {
		//  登陆状态检测  
		if (!checkLogin()) {
			return
		}
		if (defaultAddr.value === null) {
			showToast('请设置地址')
			setTimeout(() => {
				router.push('/addressList')
			}, 500)
			return
		}

		console.log(activeSku.value._id)


		let {
			_id: sku_id,
			sku_name,
			image,
			price,
			stock,
			goods_id,
			goods_name
		} = activeSku.value

		const params = {
			sku_id,
			buy_num: buy_num.value,
			sku_name,
			image,
			price,
			stock,
			goods_id,
			goods_name,
			"action_checked": true
		}

		addCartApi(params).then(res => {
			console.log(res)
			if (res.code === 0) {
				showToast(res.msg)
			} else {
				showToast(res.msg)
			}
			popupState.value = false

		})



	}

	function buy() {

		if (!checkLogin()) {
			return
		}
		if (defaultAddr.value === null) {
			showToast('请设置地址')
			setTimeout(() => {
				router.push('/addressList')
			}, 500)
			return
		}

		let {
			_id: sku_id,
			goods_id,
		} = activeSku.value
		const params = {
			"mode": "buy", //  立即
			"add_key": false,
			"address_id": defaultAddr._id,
			"cart_list": [{
				sku_id,
				buy_num: buy_num.value,
				goods_id
			}],
			"used_coupon_id": ""
		}


		router.push('/confirmOrder?data=' + JSON.stringify(params))
		popupState.value = false
	}

	return {
		addCart,
		buy
	}
}